<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus'
import http from '@/utils/http'
import { View, Hide } from '@element-plus/icons-vue'

interface FormData {
  username: string
  email: string
  password: string
  confirmPassword: string
}

const router = useRouter()
const formRef = ref() // 添加表单引用
const showPassword = ref(false)
const form = ref<FormData>({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

const validatePassword = (rule: any, value: string, callback: any) => {
  if (value !== form.value.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在1到20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ]
}

const handleRegister = async () => {
  try {
    await formRef.value.validate() // 先验证表单
    
    const data: any = await http.post('/user/register/', {
      username: form.value.username,
      email: form.value.email,
      password: form.value.password
    })
    
    if (data.message === '注册成功') {
      ElMessage.success('注册成功，请登录！')
      router.push('/login')
    } else {
      ElMessage.error(data.message || '注册失败')
    }
  } catch (error: any) {
    if (error?.errors) return // 表单验证错误不处理
    const errorMsg = error.response?.data?.message || '注册失败'
    ElMessage.error(errorMsg)
    console.error('注册失败:', error)
  }
}
</script>

<template>
    <div class="background-image"></div>
        <div>
          <div class="text-center mb-8">
            <h2 class="title-gradient">创建新账户</h2>
            <span>👋 </span>
            <h3 class="subtitle-gradient">加入考研信息交流平台</h3>
          </div>
        <div class="bg-white">
          <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
            <el-form-item label="用户名" prop="username">
              <el-input 
                v-model="form.username" 
                placeholder="请输入用户名"
              />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input 
                v-model="form.email" 
                placeholder="请输入邮箱"
                type="email"
              />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input 
                v-model="form.password" 
                :type="showPassword ? 'text' : 'password'" 
                placeholder="请输入密码"
              >
                <template #suffix>
                  <el-icon 
                    @click="showPassword = !showPassword" 
                    style="cursor: pointer; font-size: 16px;"
                  >
                    <component :is="showPassword ? Hide : View" />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                v-model="form.confirmPassword" 
                type="password" 
                placeholder="请再次输入密码"
              >
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleRegister">注册</el-button>
            </el-form-item>
          </el-form>
          <div class="w-full block mt-2 system-xs-regular text-text-tertiary">
            已有账户？<a href="/login">立即登录</a>
          </div>
        </div>
      </div>
</template>

<style scoped>
.register-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  position: relative;
}

.background-image {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('@/assets/登录注册背景.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  z-index: -1; /* 改为-1确保在内容层下方 */
  opacity: 0.9; /* 增加不透明度 */
}

/* 表单容器样式增强 */
.bg-white {
  background-color: whitesmoke;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 4px 20px white;
}


.title-gradient {
  font-size: 2.5rem;
  font-weight: bold;
  background: linear-gradient(to right, #ebece3, #8B5CF6, #EC4899);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  margin-bottom: 0.5rem;
}

.subtitle-gradient {
  font-size: 1.75rem;
  font-weight: 600;
  background: linear-gradient(to right, #d5d6cd, #4299E1);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

</style>
